<?php
/**
 * php GEM Project
 * 
 * LICENSE
 * 
 * PHP System Architecture Enabling Rapid Application Deployment and Scalability
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 * 
 * @copyright Copyright (C) 2010 Zeletron LLC (http://zeletron.com)
 * @license http://gem.zeletron.com/license
 */

/**
 * GEM/Filter/File.php
 * 
 * This class provides common user input filters that streamline
 * the filtering of files.
 * 
 * @author David Joly
 * @category GEM
 * @package GEM_Filter
 */

class GEM_Filter_File
{	
	/**
	 * Clean Filename
	 * Filters a filename per given options and returns the filtered file name.
	 * If no options are passed, the defaults will be used.
	 * 
	 * $options = array(
	 *			'length' 		=> 50,		//Max length for filename, including extension
	 *			'ext' 			=> true,    //If true, the filename's extsion will be included 
	 *			'alnum' 		=> true,    //If true, an alnum filter will be applied.  
	 *			'whitespace'	=> '_'      //Sets the character with which to replace whitespace
	 *		);
	 * 
	 * @param string $basename
	 * @param array $options
	 * @return string
	 */
	public static function cleanFilename($basename,array $options = null)
	{
		if(!$options) {
			$options = array(
				'length' 		=> 50,
				'ext' 			=> true, 
				'alnum' 		=> true, 
				'whitespace'	=> '_'
			);
		}
		$parts = pathinfo($basename);
		$ext = $parts['extension'];
		$filename = $parts['filename'];
		
		//Apply Alnum filter if specified
    	if($options['alnum']){
    		$alnum = new Zend_Filter_Alnum(true);
    		$filename = $alnum->filter($filename);
    	}
    	//Replace spaces with underscores
    	$filename = str_replace(' ',$options['whitespace'],$filename);

    	//Return final string at less <= 50 characters.
    	if($options['ext'] == true){
    		$filename = substr($filename,0,$options['length'] - (strlen($ext)+1));
    		return $filename . '.' . $ext;
    	}else{
    		$filename = substr($filename,0,$options['length']); 
			return $filename;
    	}
		
	}
}
